<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Model\AdminLogsModel;
use App\Model\AdminRolesModel;
use App\Model\AdminNodeRoleModel;
use App\Model\AdminNodeModel;
use App\Model\AdminTypeModel;
use Validator;

//角色
class RolesController extends Controller
{
    // 列表
    public function index(Request $request,AdminRolesModel $arModel)
    {
        //搜索条件
        $keywords = $request->input('keywords');//关键字
        $month = $request->input('month');//时间

        $pageParam['keywords'] = $keywords;
        $pageParam['month'] = $month;

        $list = $arModel
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('name', 'like', "%{$keywords}%");
            })
            ->when($month, function ($query) use ($month) {
                $month_arr = explode("~",$month);
                $mintime = $month_arr[0];
                $maxtime = $month_arr[1]." 23:59:59";
                return $query->whereBetween('created_at', [$mintime,$maxtime]);
            })
            ->orderBy('id', 'desc')
            ->paginate(10);
        // dump($list);
        //分页
        $page = $list->appends($pageParam)->links();

        return view('admin.role.index')
            ->with('keywords',$keywords)
            ->with('month',$month)
            ->with('page',$page)
            ->with('list',$list);
    }

    //添加页
    public function add(Request $request,AdminTypeModel $atModel)
    {
        //所有权限
        $list = $atModel->listAll();
        // dd($list);

        return view('admin.role.add')
            ->with('list',$list);
    }

    //添加操作
    public function insert(Request $request,AdminRolesModel $arModel,AdminNodeRoleModel $anrModel)
    {
        $post = $request->post();
        $validator = Validator::make($post,[
          'name'=>'required',
        ],[
          'name.required' => '角色名不能为空',
        ]);
        if($validator->fails()){
          return returnJson(0, $validator->errors()->first());
        }

        //事物
        DB::beginTransaction();
        try {
            //添加角色
            $newid = $arModel->insertGetId(['name'=>$post['name'],'remark'=>$post['remark']]);
            //角色-权限
            if($request->filled('node')){
                $node = $request->post('node');
                foreach ($node as $v) {
                    $anrModel->insert(['node_id'=>$v,'role_id'=>$newid]);
                }
            }
            //添加日志
            $msg = "添加角色【".$post['name']."】(id:".$newid.")";
            AdminLogsModel::addLog($msg);

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
            return returnJson(0,'操作失败,请稍后再试');
        }
        return returnJson(1,'操作成功');
    }

    //编辑页
    public function edit(Request $request,AdminTypeModel $atModel)
    {
        //所有权限
        $nodeList = $atModel->listAll();


        //角色信息
        $id = $request->post('id');//id
        $res = AdminRolesModel::with('nodes')
            ->where('id',$id)
            ->first();
        foreach($res->nodes as $k=>$v){
        	if($v['state'] == 2){
        		unset($res->nodes[$k]);
			}
		}
        //拥有权限
        $nodes = [];
        foreach ($res->nodes as $v) {
            array_push($nodes,$v['id']);
        }


        return view('admin.role.edit')
            ->with('res',$res)
            ->with('nodes',$nodes)
            ->with('nodeList',$nodeList);
    }

    //编辑操作
    public function update(Request $request,AdminRolesModel $arModel,AdminNodeRoleModel $anrModel)
    {
        // $post = $request->post();
        $validator = Validator::make($request->post(),[
          'id'=>'required',
          'name'=>'required',
        ],[
          'id.required' => 'id不能为空',
          'name.required' => '角色名不能为空',
        ]);
        if($validator->fails()){
          return returnJson(0, $validator->errors()->first());
        }
        $id = $request->post('id');
        $name = $request->post('name');
        $remark = $request->post('remark');

        //事物
        DB::beginTransaction();
        try {
            //更改角色信息
            $arModel->where('id',$id)->update(['remark'=>$name,'remark'=>$remark]);
            //更改角色-权限
            $anrModel->where('role_id',$id)->delete();

            if($request->filled('node')){
                $node = $request->post('node');
                foreach ($node as $v) {
                    $anrModel->insert(['node_id'=>$v,'role_id'=>$id]);
                }
            }
            //添加日志
            $msg = "编辑角色【".$name."】(id:".$id.")信息";
            AdminLogsModel::addLog($msg);

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
            return returnJson(0,'操作失败,请稍后再试');
        }
        return returnJson(1,'操作成功');
    }

    //删除操作
    public function del(Request $request,AdminRolesModel $arModel)
    {
        $id = $request->post('id');//id
        $returnArr = $arModel->delId($id);
        return response()->json($returnArr);
    }

}
